package com.itpan.Utils;



import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.itpan.Entity.PurchaseOrder;
import com.itpan.Service.EmployeeService;
import com.itpan.Service.PurchaseOrderService;


import java.util.ArrayList;
import java.util.List;

public class PurchaseOrderExcelListener extends AnalysisEventListener<PurchaseOrder> {

    private final PurchaseOrderService purchaseOrderService;

    private final EmployeeService employeeService;

    private final EntityValidate entityValidate;
    private List<PurchaseOrder> purchaseOrderList = new ArrayList<>();

    public PurchaseOrderExcelListener(PurchaseOrderService purchaseOrderService, EmployeeService employeeService, EntityValidate entityValidate) {
        this.purchaseOrderService = purchaseOrderService;
        this.employeeService = employeeService;
        this.entityValidate = entityValidate;
    }

    @Override
    public void invoke(PurchaseOrder purchaseOrder, AnalysisContext context) {
        // 校验数据是否有效
        if (isValidPurchaseOrder(purchaseOrder) && !isAlreadyRegistered(purchaseOrder) && isExitEmployee(purchaseOrder)&& entityValidate.isValidateOfPurchaseOrder(purchaseOrder)) {
            purchaseOrderList.add(purchaseOrder);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 读取结束后的操作，可以进行批量保存或其他处理
        if (!purchaseOrderList.isEmpty()) {
            purchaseOrderService.saveAll(purchaseOrderList);
        }
    }

    private boolean isValidPurchaseOrder(PurchaseOrder purchaseOrder) {
        // 检查每个字段是否为null或空
        return purchaseOrder.getEmployeeID() != null
                && purchaseOrder.getQuantity() != null
                && purchaseOrder.getTotalPrice() != null
                && purchaseOrder.getOrderDate() != null
                && purchaseOrder.getNotes() != null;
    }

    private boolean isAlreadyRegistered(PurchaseOrder purchaseOrder) {
        PurchaseOrder existingPurchaseOrder = purchaseOrderService.getById(purchaseOrder.getOrderID());
        return existingPurchaseOrder != null;
    }

    private boolean isExitEmployee(PurchaseOrder purchaseOrder){
        return employeeService.getById(purchaseOrder.getEmployeeID())!=null;
    }
}
